package com.hopscotch.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Component
public class JwtUtils {
    @Value("${token.header}")
    private String header;
    @Value("${token.secret}")
    private String secret;
    @Value("${token.expireTime}")
    private Integer expireTime;
    @Autowired
    private RedisUtil redisUtil;
    //创建Token
    public String creatToken(HashMap<String, Object> map){
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, secret).setClaims(map).compact();
        return token;
    }
    //解析Token
    public Claims parserToken(String token){
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        return claims;
    }

    //获取请求头中的Token，一般在认证过滤器中使用
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        //封装后的工具类，用于对比字符串是存在且不为空
        if (StringUtils.hasText(token)) {
            return token;
        }
        return null;
    }

    public void saveToken(String token){
        Claims claims = this.parserToken(token);
        if (claims != null){
            String uid = (String)claims.get("uid");
            redisUtil.setCacheObject("uid:" + uid,token,60000, TimeUnit.MINUTES);
        }
    }

    public String getRedisToken(String uid) throws Exception {
        String token = redisUtil.getCacheObject("uid:" + uid);
        if (token == null){
            throw new Exception("token失效");
        }else {
            redisUtil.expire("uid:" + uid,60000,TimeUnit.SECONDS);
            return token;
        }
    }

}

